package com.test.springboot.controller;

import com.test.springboot.dao.DepartmentDao;
import com.test.springboot.dao.EmployeeDao;
import com.test.springboot.entities.Department;
import com.test.springboot.entities.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;

/**
 * 员工相关请求处理
 *
 * @author: ybl
 * @create: 2019-05-15 14:21
 **/
@Controller
public class EmployeeController {

    @Autowired
    private EmployeeDao employeeDao;

    @Autowired
    private DepartmentDao departmentDao;

    //查询所有员工返回列表页面
    @GetMapping("/emps")
    public String list(Model model) {
        //查询员工
        Collection<Employee> employees = employeeDao.getAll();
        //将查询结果放在请求域中
        model.addAttribute("emps", employees);

        return "emp/list";
    }

    //跳转到添加员工页面
    @GetMapping("emp")
    public String toAddPage(Model model) {
        //添加员工之前,查询所有的部门名称
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("depts", departments);

        return "emp/add";
    }

    //添加员工
    @PostMapping("emp")
    public String addEmp(Employee employee) {
        //保存员工
        employeeDao.save(employee);

        //添加员工成功后跳转到员工列表页面
        //redirect:重定向到一个地址,/代表当前项目路径
        //forward:表示请求转发到一个地址
        return "redirect:/emps";
    }

    //根据id查询员工,并跳转到修改页面
    @GetMapping("/emp/{id}")
    public String toEditPage(@PathVariable("id") Integer id, Model model) {
        //查询员工
        Employee employee = employeeDao.get(id);
        model.addAttribute("emp", employee);

        //部门列表显示
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("depts", departments);

        //跳转到编辑页面,与添加是同一个页面
        return "emp/add";
    }

    //修改员工,注意员工Id的传入
    @PutMapping("emp")
    public String updateEmployee(Employee employee) {
        //修改员工信息
        employeeDao.save(employee);

        return "redirect:/emps";
    }

    //删除员工
    @DeleteMapping("emp/{id}")
    public String deleteEmployee(@PathVariable("id") Integer id) {
        employeeDao.delete(id);

        return "redirect:/emps";
    }
}
